package com.ywgt.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * A-B-C顺序执行
 */
public class ByOrder {
    public static void main(String[] args) {
        C c=new C();
        new Thread(()->{
          for (int i=0;i<10;i++){
              c.printA();
          }
        },"A").start();
        new Thread(()->{
            for (int i=0;i<10;i++){
                c.printB();
            }
        },"B").start();
        new Thread(()->{
            for (int i=0;i<10;i++){
                c.printC();
            }
        },"C").start();
    }
}
class C{
    private Integer num=1;

    Lock lock=new ReentrantLock();
    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();
    Condition conditionC = lock.newCondition();

    public void printA(){
        lock.lock();
        try {
            while (num!=1){
                conditionA.await();
            }
            num=2;
            System.out.println(Thread.currentThread().getName()+num);
            //唤醒指定的线程
            conditionB.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
    public void printB(){
        lock.lock();
        try {
            while (num!=2){
                conditionB.await();
            }
            num=3;
            System.out.println(Thread.currentThread().getName()+num);
            //唤醒指定的线程
            conditionC.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
    public void printC(){
        lock.lock();
        try {
            while (num!=3){
                conditionC.await();
            }
            num=1;
            System.out.println(Thread.currentThread().getName()+num);
            //唤醒指定的线程
            conditionA.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}